package com.tushare.util;

import com.tushare.entity.IndexMean;

import java.util.ArrayList;
import java.util.List;

public class SortUtil {
    private static final double ZERO_DOUBLE = 1e-10;
    private static final List<Integer> indexList = new ArrayList<>();

    public static int compareFloat(float one, float two) {
        if (one - two > ZERO_DOUBLE) {
            return 1;
        } else if (two - one > ZERO_DOUBLE) {
            return -1;
        } else {
            return 0;
        }
    }

    public static List<IndexMean> sortIndexMean(String ts_code, String index_type, List<Float> list) {
        initIndexList();
        List<IndexMean> indexMeanList = new ArrayList<>();
        indexList.forEach(index -> indexMeanList.add(new IndexMean(ts_code, index, index_type,
                calMeanValue(index, list.size() - 1, list))));
        return indexMeanList;
    }

    private static void initIndexList() {
        if (indexList.size() == 0) {
            for (int index = 0; index <= 20; index++) {
                indexList.add(index * 5);
            }
        }
    }

    private static float calMeanValue(int percentage, int maxListIndex, List<Float> list) {
        float index = maxListIndex * percentage / 100.0f;
        int minIndex = (int) Math.floor(index);
        int maxIndex = minIndex + 1;
        if (maxIndex > maxListIndex) {
            maxIndex = maxListIndex;
        }
        float minValue = list.get(minIndex);
        float maxValue = list.get(maxIndex);
        return minValue + (index - minIndex) * (maxValue - minValue);
    }

}
